package com.shuxinxin.test.controller;


import com.shuxinxin.test.pojo.Result;
import com.shuxinxin.test.pojo.User;
import com.shuxinxin.test.service.UserService;
import com.shuxinxin.test.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Result login(@RequestParam("username") String username, @RequestParam("password") String password) {
        User loginUser = userService.login(username, password);
        //        查询返回结果为空
        if(loginUser == null){
            return Result.error("账号或密码错误");
        }

        if(loginUser.getPassword().equals(password) ){
            Map<String , Object> map = new HashMap<>();
            map.put("username",username);
            map.put("password",password);
            String token = JwtUtil.genToken(map);
            return Result.success(token);
        }
        return Result.error("账号或密码错误");
    }

    //    注册
    @PostMapping("/reg")
    public Result reg(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("nickname") String nickname) {
        User reg = userService.selectUser(username);
        if (reg != null) {
            return Result.error("账号已存在");
        }
        int reg1 = userService.reg(username, password, nickname);
        if (reg1 != 0) return Result.success();
        return Result.error("请求失败");
    }
}
